<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">











<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Javascript,">










<meta name="description" content="从JS基础知识到JS-WEB-APIjs基础知识：基于ECMA 262标准（规定基础语法、规则）  –变量类型和计算–原型和原型链–闭包和作用域–异步和单线程–其他（如日期、Math、各种常用API）   特点：表面看来并不能用于工作中开发代码 内置函数：Object Array Boolean String… 内置对象：Math JSON…  js-web-API：基于W3C标准（在规则上怎么用">
<meta name="keywords" content="Javascript">
<meta property="og:type" content="article">
<meta property="og:title" content="JS-Web-API（BOM、DOM、事件、Ajax、存储）">
<meta property="og:url" content="elfeach.gitee.io/2020/10/29/JS-Web-API-DOM/index.html">
<meta property="og:site_name" content="Elfecho’Blog">
<meta property="og:description" content="从JS基础知识到JS-WEB-APIjs基础知识：基于ECMA 262标准（规定基础语法、规则）  –变量类型和计算–原型和原型链–闭包和作用域–异步和单线程–其他（如日期、Math、各种常用API）   特点：表面看来并不能用于工作中开发代码 内置函数：Object Array Boolean String… 内置对象：Math JSON…  js-web-API：基于W3C标准（在规则上怎么用">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-11-01T13:10:32.917Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JS-Web-API（BOM、DOM、事件、Ajax、存储）">
<meta name="twitter:description" content="从JS基础知识到JS-WEB-APIjs基础知识：基于ECMA 262标准（规定基础语法、规则）  –变量类型和计算–原型和原型链–闭包和作用域–异步和单线程–其他（如日期、Math、各种常用API）   特点：表面看来并不能用于工作中开发代码 内置函数：Object Array Boolean String… 内置对象：Math JSON…  js-web-API：基于W3C标准（在规则上怎么用">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"没有找到与[${query}]相关的内容","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="elfeach.gitee.io/2020/10/29/JS-Web-API-DOM/">





  <title>JS-Web-API（BOM、DOM、事件、Ajax、存储） | Elfecho’Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?c491056d7021e5c248129f6222a89004";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  
  <script type="text/javascript" src="/js/src/crash_cheat.js"></script>
  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Elfecho’Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">有空时来歇歇脚吧</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="elfeach.gitee.io/2020/10/29/JS-Web-API-DOM/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="elfecho">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Elfecho’Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JS-Web-API（BOM、DOM、事件、Ajax、存储）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-29T21:47:27+08:00">
                2020-10-29
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            
            
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.3k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  15 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="从JS基础知识到JS-WEB-API"><a href="#从JS基础知识到JS-WEB-API" class="headerlink" title="从JS基础知识到JS-WEB-API"></a>从JS基础知识到JS-WEB-API</h1><p><strong>js基础知识：</strong>基于ECMA 262标准（规定基础语法、规则）</p>
<blockquote>
<p>–变量类型和计算<br>–原型和原型链<br>–闭包和作用域<br>–异步和单线程<br>–其他（如日期、Math、各种常用API）</p>
</blockquote>
<ol>
<li>特点：表面看来并不能用于工作中开发代码</li>
<li>内置函数：Object Array Boolean String…</li>
<li>内置对象：Math JSON…</li>
</ol>
<p><strong>js-web-API：</strong>基于W3C标准（在规则上怎么用）</p>
<blockquote>
<p>w3c标准中关于JS的规定有：<br>–DOM操作（增删改查，修改网页的结构，页面的动态效果）<br>–BOM操作（获取浏览器特性、当前屏幕尺寸宽高、当前地址栏地址）<br>–事件绑定（click，keyon，mouseenter，mouseup等）<br>–ajax请求（包括http协议）<br>–存储</p>
</blockquote>
<h1 id="DOM"><a href="#DOM" class="headerlink" title="DOM"></a>DOM</h1><p><strong>Document Object Model</strong>的简称</p>
<ol>
<li><strong>DOM是哪种基本的数据结构？</strong></li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">--树(DOM树)</span><br></pre></td></tr></table></figure>
<ol start="2">
<li><strong>DOM操作的常用API有哪些？</strong></li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">--获取DOM节点，以及节点的property和Attribute</span><br><span class="line">--获取父节点，获取子节点</span><br><span class="line">--新增节点，删除节点</span><br></pre></td></tr></table></figure>
<ol start="3">
<li><strong>DOM节点的attribute和property有何区别？</strong></li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">--property：修改对象属性，不会体现到html结构上（优先使用）</span><br><span class="line">--Attribute：修改html属性，会改变html结构</span><br><span class="line">两者都有可能引起DOM重新渲染</span><br></pre></td></tr></table></figure>
<h2 id="DOM的本质"><a href="#DOM的本质" class="headerlink" title="DOM的本质"></a><strong>DOM的本质</strong></h2><p>（浏览器把拿到的html代码，结构化成浏览器可识别、js可操作的一个模型而已）</p>
<blockquote>
<p>–XML可扩展的描述语言，可以描述任何结构化的数据<br>树，有一个主干，有很多分支，分支在有分支；</p>
</blockquote>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version="1.0" encoding="UTF-8"&gt;</span><br><span class="line">&lt;note&gt;</span><br><span class="line">    &lt;to&gt;Tove&lt;/to&gt;</span><br><span class="line">    &lt;from&gt;Jani&lt;/from&gt;</span><br><span class="line">    &lt;heading&gt;Reminder&lt;/heading&gt;</span><br><span class="line">    &lt;boby&gt;Don't forget me this weekend!&lt;/body&gt;</span><br><span class="line">    &lt;other&gt;</span><br><span class="line">        &lt;a&gt;&lt;/a&gt;</span><br><span class="line">        &lt;b&gt;&lt;/b&gt;</span><br><span class="line">    &lt;/other&gt;</span><br><span class="line">&lt;/note&gt;</span><br></pre></td></tr></table></figure>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">--</span> <span class="attr">html</span>是<span class="attr">XML</span>的一种特殊类型，是一种特殊结构，和<span class="attr">XML</span>一样的规则 <span class="attr">--</span>&gt;</span></span><br><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span> =<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">p</span>&gt;</span>this is p!<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="DOM节点操作"><a href="#DOM节点操作" class="headerlink" title="DOM节点操作"></a><strong>DOM节点操作</strong></h2><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"ie=edge"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>dom 演示<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">style</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="css">            <span class="selector-class">.container</span> &#123;</span></span><br><span class="line"><span class="css">                <span class="selector-tag">border</span>: 1<span class="selector-tag">px</span> <span class="selector-tag">solid</span> <span class="selector-id">#ccc</span>;</span></span><br><span class="line"><span class="undefined">            &#125;</span></span><br><span class="line"><span class="css">            <span class="selector-class">.red</span> &#123;</span></span><br><span class="line"><span class="undefined">                color: red;</span></span><br><span class="line"><span class="undefined">            &#125;</span></span><br><span class="line"><span class="undefined">        </span><span class="tag">&lt;/<span class="name">style</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"div1"</span> <span class="attr">class</span>=<span class="string">"container"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">p</span> <span class="attr">id</span>=<span class="string">"p1"</span>&gt;</span>一段文字 1<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">p</span>&gt;</span>一段文字 2<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">p</span>&gt;</span>一段文字 3<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"div2"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"https://img3.mukewang.com/5a9fc8070001a82402060220-100-100.jpg"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">ul</span> <span class="attr">id</span>=<span class="string">"list"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"./dom-1.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>获取DOM节点</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> divList = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'div'</span>) <span class="comment">// 集合</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'divList.length'</span>, divList.length)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'divList[1]'</span>, divList[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> containerList = <span class="built_in">document</span>.getElementsByClassName(<span class="string">'container'</span>) <span class="comment">// 集合</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'containerList.length'</span>, containerList.length)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'containerList[1]'</span>, containerList[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> pList = <span class="built_in">document</span>.querySelectorAll(<span class="string">'p'</span>)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'pList'</span>, pList)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> pList = <span class="built_in">document</span>.querySelectorAll(<span class="string">'p'</span>)</span><br><span class="line"><span class="keyword">const</span> p1 = pList[<span class="number">0</span>]</span><br></pre></td></tr></table></figure>
<ul>
<li>property(改的是js对象的一个标准属性)</li>
</ul>
<p>通过修改或者获取js的属性来改变页面样式、页面渲染结构的一种形式，Dom结构js变量的修改</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> pList = <span class="built_in">document</span>.querySelectorAll(<span class="string">'p'</span>)</span><br><span class="line"><span class="keyword">const</span> p1 = pList[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">// property 形式</span></span><br><span class="line">p1.style.width = <span class="string">'100px'</span></span><br><span class="line"><span class="built_in">console</span>.log( p1.style.width )</span><br><span class="line">p1.className = <span class="string">'red'</span></span><br><span class="line"><span class="built_in">console</span>.log( p1.className )</span><br><span class="line"><span class="built_in">console</span>.log(p1.nodeName) <span class="comment">// P</span></span><br><span class="line"><span class="built_in">console</span>.log(p1.nodeType) <span class="comment">// 1</span></span><br></pre></td></tr></table></figure>
<ul>
<li>attribute(改的html代码文档里面的标签的属性)</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">p1.setAttribute(<span class="string">'data-name'</span>, <span class="string">'imooc'</span>)</span><br><span class="line"><span class="built_in">console</span>.log( p1.getAttribute(<span class="string">'data-name'</span>) )</span><br><span class="line">p1.setAttribute(<span class="string">'style'</span>, <span class="string">'font-size: 50px;'</span>)</span><br><span class="line"><span class="built_in">console</span>.log( p1.getAttribute(<span class="string">'style'</span>) )</span><br></pre></td></tr></table></figure>
<p>小结</p>
<ol>
<li>property：修改对象属性，不会体现到html结构中</li>
<li>attribute：修改html属性，会改变html结构</li>
<li>两者都有可能引起DOM重新渲染</li>
<li>最好使用property</li>
</ol>
<h2 id="DOM结构操作"><a href="#DOM结构操作" class="headerlink" title="DOM结构操作"></a>DOM结构操作</h2><ul>
<li>新增/插入节点</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> div1 = <span class="built_in">document</span>.getElementById(<span class="string">'div1'</span>)</span><br><span class="line"><span class="keyword">const</span> div2 = <span class="built_in">document</span>.getElementById(<span class="string">'div2'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 新建节点</span></span><br><span class="line"><span class="keyword">const</span> newP = <span class="built_in">document</span>.createElement(<span class="string">'p'</span>)</span><br><span class="line">newP.innerHTML = <span class="string">'this is newP'</span></span><br><span class="line"><span class="comment">// 插入节点</span></span><br><span class="line">div1.appendChild(newP)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 移动节点</span></span><br><span class="line"><span class="keyword">const</span> p1 = <span class="built_in">document</span>.getElementById(<span class="string">'p1'</span>)</span><br><span class="line">div2.appendChild(p1)</span><br></pre></td></tr></table></figure>
<ul>
<li>获取子元素列表，获取父元素</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取父元素</span></span><br><span class="line"><span class="built_in">console</span>.log( p1.parentNode )</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取子元素列表</span></span><br><span class="line"><span class="keyword">const</span> div1ChildNodes = div1.childNodes</span><br><span class="line"><span class="built_in">console</span>.log( div1.childNodes )<span class="comment">//还会含有text文本标签，nodeType 等于3</span></span><br><span class="line"><span class="keyword">const</span> div1ChildNodesP = <span class="built_in">Array</span>.prototype.slice.call(div1.childNodes).filter(<span class="function"><span class="params">child</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (child.nodeType === <span class="number">1</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">&#125;)</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'div1ChildNodesP'</span>, div1ChildNodesP)</span><br></pre></td></tr></table></figure>
<ul>
<li>删除子元素</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">div1.removeChild( div1ChildNodesP[<span class="number">0</span>] )</span><br></pre></td></tr></table></figure>
<h2 id="DOM性能"><a href="#DOM性能" class="headerlink" title="DOM性能"></a>DOM性能</h2><ul>
<li>避免频繁的DOM操作</li>
<li>对DOM查询做缓存</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//不缓存 DOM 查询结果</span></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; <span class="built_in">document</span>.getElementsByTagName(<span class="string">'p'</span>).length; i++)&#123;</span><br><span class="line">	<span class="comment">//每次循环，都会计算length，频繁进行DOM查询</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//缓存 DOM 查询结果</span></span><br><span class="line"><span class="keyword">const</span> pList = <span class="built_in">document</span>.getElementsByTagName(<span class="string">'p'</span>)</span><br><span class="line"><span class="keyword">const</span> length = pList.length</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; length ; i++)&#123;</span><br><span class="line">	<span class="comment">//缓存length，只进行一次DOM查询</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>将频繁操作改为一次性操作，一次性插入多个节点，考虑性能</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> list = <span class="built_in">document</span>.getElementById(<span class="string">'list'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 创建一个文档片段，此时还没有插入到 DOM 结构中</span></span><br><span class="line"><span class="keyword">const</span> frag = <span class="built_in">document</span>.createDocumentFragment()</span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> i  = <span class="number">0</span>; i &lt; <span class="number">20</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">const</span> li = <span class="built_in">document</span>.createElement(<span class="string">'li'</span>)</span><br><span class="line">    li.innerHTML = <span class="string">`List item <span class="subst">$&#123;i&#125;</span>`</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 先插入文档片段中</span></span><br><span class="line">    frag.appendChild(li)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 都完成之后，再统一插入到 DOM 结构中</span></span><br><span class="line">list.appendChild(frag)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(list)</span><br></pre></td></tr></table></figure>
<h1 id="BOM"><a href="#BOM" class="headerlink" title="BOM"></a>BOM</h1><blockquote>
<p>JS 浏览器对象模型（Browser Object Model, BOM）被广泛应用于 Web 开发之中，主要用于客户端浏览器的管理</p>
</blockquote>
<ul>
<li>navigator（浏览器信息）</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> ua = navigator.userAgent</span><br><span class="line"><span class="keyword">const</span> isChrome = ua.indexOf(<span class="string">'Chrome'</span>)</span><br><span class="line"><span class="built_in">console</span>.log(isChrome)</span><br></pre></td></tr></table></figure>
<ul>
<li>location（地址信息）</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(location.href)</span><br><span class="line"><span class="built_in">console</span>.log(location.protocol) <span class="comment">//http:或https:</span></span><br><span class="line"><span class="built_in">console</span>.log(location.pathname)</span><br><span class="line"><span class="built_in">console</span>.log(location.search)</span><br><span class="line"><span class="built_in">console</span>.log(location.hash)</span><br></pre></td></tr></table></figure>
<ul>
<li>history（前进后退信息）</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">history.back()</span><br><span class="line">history.forward()</span><br></pre></td></tr></table></figure>
<h1 id="事件"><a href="#事件" class="headerlink" title="事件"></a>事件</h1><h2 id="事件绑定"><a href="#事件绑定" class="headerlink" title="事件绑定"></a>事件绑定</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> btn = <span class="built_in">document</span>.getElementById(<span class="string">'btn1'</span>)</span><br><span class="line">btn.addEventListener(<span class="string">'click'</span>, event =&gt; &#123;</span><br><span class="line">	<span class="built_in">console</span>.log(<span class="string">'clicked'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">//通用的绑定函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">bindEvent</span>(<span class="params">elem,type,fn</span>)</span>&#123;</span><br><span class="line">	elem.addEventListener(type,fn)</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> a = <span class="built_in">document</span>.getElementById(<span class="string">'link1'</span>)</span><br><span class="line">bindEvent(a, <span class="string">'click'</span>, (e)=&gt; &#123;</span><br><span class="line">    <span class="comment">// console.log(event.target) // 获取触发的元素</span></span><br><span class="line">    event.preventDefault() <span class="comment">// 阻止默认行为</span></span><br><span class="line">    alert(<span class="string">'clicked'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<h2 id="事件冒泡"><a href="#事件冒泡" class="headerlink" title="事件冒泡"></a>事件冒泡</h2><p>从下向上进行冒泡</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">	&lt;div id=<span class="string">"div1"</span>&gt;</span><br><span class="line">		&lt;p id=<span class="string">"p1"</span>&gt;激活&lt;<span class="regexp">/p&gt;</span></span><br><span class="line"><span class="regexp">		&lt;p id="p2"&gt;取消&lt;/</span>p&gt;</span><br><span class="line">		&lt;p id=<span class="string">"p3"</span>&gt;取消&lt;<span class="regexp">/p&gt;</span></span><br><span class="line"><span class="regexp">		&lt;p id="p4"&gt;取消&lt;/</span>p&gt;</span><br><span class="line">	&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">	&lt;div id="div2"&gt;</span></span><br><span class="line"><span class="regexp">		&lt;p id="p5"&gt;取消&lt;/</span>p&gt;</span><br><span class="line">		&lt;p id=<span class="string">"p6"</span>&gt;取消&lt;<span class="regexp">/p&gt;</span></span><br><span class="line"><span class="regexp">	&lt;/</span>div&gt;</span><br><span class="line">&lt;<span class="regexp">/body&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">const p1 = document.getElementById('p1')</span></span><br><span class="line"><span class="regexp">const body = document.body</span></span><br><span class="line"><span class="regexp">bindEvent(p1,'click',e =&gt; &#123;</span></span><br><span class="line"><span class="regexp">	e.stopPropagation() /</span><span class="regexp">/阻止冒泡，可以注释这一行，来体会事件冒泡，没有这一行的话会先弹激活，再弹取消，有这一行只弹激活</span></span><br><span class="line"><span class="regexp">	console.log('激活')</span></span><br><span class="line"><span class="regexp">&#125;)</span></span><br><span class="line"><span class="regexp">bindEvent(body,'click',e =&gt; &#123;</span></span><br><span class="line"><span class="regexp">	console.log('取消')</span></span><br><span class="line"><span class="regexp">&#125;)</span></span><br></pre></td></tr></table></figure>
<h2 id="事件代理"><a href="#事件代理" class="headerlink" title="事件代理"></a>事件代理</h2><p>代码简洁、减少浏览器内存占用、但是不要滥用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br></pre></td><td class="code"><pre><span class="line">&lt;div id=<span class="string">"div1"</span>&gt;</span><br><span class="line">	&lt;a href=<span class="string">"#"</span>&gt;a1&lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp">	&lt;a href="#"&gt;a2&lt;/</span>a&gt;</span><br><span class="line">	&lt;a href=<span class="string">"#"</span>&gt;a3&lt;<span class="regexp">/a&gt;</span></span><br><span class="line"><span class="regexp">	&lt;a href="#"&gt;a4&lt;/</span>a&gt;</span><br><span class="line">&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">&lt;button&gt;点击增加一个a标签&lt;/</span>button&gt;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> div1 = <span class="built_in">document</span>.getElementById(<span class="string">'div1'</span>)</span><br><span class="line">bindEvent(div1,<span class="string">'click'</span>,event =&gt; &#123;</span><br><span class="line">	event.preventDefault() <span class="comment">// 阻止默认行为</span></span><br><span class="line">	<span class="keyword">const</span> target = event.target</span><br><span class="line">	<span class="keyword">if</span>(target.nodeName === <span class="string">'A'</span>)&#123;</span><br><span class="line">		alert(target.innerHTML)</span><br><span class="line">	&#125;</span><br><span class="line">&#125;)</span><br><span class="line"><span class="number">12345678910111213141516</span></span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;button id=<span class="string">"btn1"</span>&gt;一个按钮&lt;<span class="regexp">/button&gt;</span></span><br><span class="line"><span class="regexp">    &lt;div id="div3"&gt;</span></span><br><span class="line"><span class="regexp">        &lt;a href="#"&gt;a1&lt;/</span>a&gt;<span class="xml"><span class="tag">&lt;<span class="name">br</span>&gt;</span></span></span><br><span class="line">        &lt;a href="#"&gt;a2&lt;/a&gt;&lt;br&gt;</span><br><span class="line">        &lt;a href="#"&gt;a3&lt;/a&gt;&lt;br&gt;</span><br><span class="line">        &lt;a href="#"&gt;a4&lt;/a&gt;&lt;br&gt;</span><br><span class="line">        &lt;button&gt;加载更多...&lt;/button&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">//通用的事件绑定函数，兼容事件绑定和事件代理</span><br><span class="line">function bindEvent(elem, type, selector, fn) &#123;</span><br><span class="line">    if (fn == null) &#123;</span><br><span class="line">        fn = selector</span><br><span class="line">        selector = null</span><br><span class="line">    &#125;</span><br><span class="line">    elem.addEventListener(type, event =&gt; &#123;</span><br><span class="line">        const target = event.target</span><br><span class="line">        if (selector) &#123;</span><br><span class="line">            // 代理绑定</span><br><span class="line">            if (target.matches(selector)) &#123;</span><br><span class="line">                fn.call(target, event)</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; else &#123;</span><br><span class="line">            // 普通绑定</span><br><span class="line">            fn.call(target, event)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">// 普通绑定</span><br><span class="line">const btn1 = document.getElementById('btn1')</span><br><span class="line">bindEvent(btn1, 'click', function (event) &#123;</span><br><span class="line">    // console.log(event.target) // 获取触发的元素</span><br><span class="line">    event.preventDefault() // 阻止默认行为</span><br><span class="line">    alert(this.innerHTML)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">// 代理绑定</span><br><span class="line">const div3 = document.getElementById('div3')</span><br><span class="line">bindEvent(div3, 'click', 'a', function (event) &#123;</span><br><span class="line">    event.preventDefault()</span><br><span class="line">    alert(this.innerHTML)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//描述事件冒泡的流程</span></span><br><span class="line">基于DOM树形结构</span><br><span class="line">事件会顺着触发元素往上冒泡</span><br><span class="line">应用场景：代理</span><br><span class="line"></span><br><span class="line"><span class="comment">//无限下拉的图片列表，如何监听每个图片的点击</span></span><br><span class="line">事件代理</span><br><span class="line">用e.target获取触发元素</span><br><span class="line">用matches来判断是否是触发元素</span><br></pre></td></tr></table></figure>
<h1 id="Ajax"><a href="#Ajax" class="headerlink" title="Ajax"></a>Ajax</h1><h2 id="XMLHttpRequest"><a href="#XMLHttpRequest" class="headerlink" title="XMLHttpRequest"></a>XMLHttpRequest</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//get请求</span></span><br><span class="line"><span class="keyword">const</span> xhr = <span class="keyword">new</span> XMLHttpRequest()</span><br><span class="line">xhr.open(<span class="string">'GET'</span>, <span class="string">'/data/test.json'</span>, <span class="literal">true</span>) <span class="comment">//true为异步，false为同步</span></span><br><span class="line">xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="comment">//这里的函数异步执行</span></span><br><span class="line">    <span class="keyword">if</span> (xhr.readyState === <span class="number">4</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xhr.status === <span class="number">200</span>) &#123;</span><br><span class="line">            <span class="comment">// console.log(</span></span><br><span class="line">            <span class="comment">//     JSON.parse(xhr.responseText)</span></span><br><span class="line">            <span class="comment">// )</span></span><br><span class="line">            alert(xhr.responseText)</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (xhr.status === <span class="number">404</span>) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'404 not found'</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">xhr.send(<span class="literal">null</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">//post请求</span></span><br><span class="line"><span class="keyword">const</span> xhr = <span class="keyword">new</span> XMLHttpRequest()</span><br><span class="line">xhr.open(<span class="string">'POST'</span>, <span class="string">'/login'</span>, <span class="literal">true</span>) <span class="comment">//true为异步，false为同步</span></span><br><span class="line">xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">	<span class="comment">//这里的函数异步执行</span></span><br><span class="line">    <span class="keyword">if</span> (xhr.readyState === <span class="number">4</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span> (xhr.status === <span class="number">200</span>) &#123;</span><br><span class="line">            <span class="comment">// console.log(</span></span><br><span class="line">            <span class="comment">//     JSON.parse(xhr.responseText)</span></span><br><span class="line">            <span class="comment">// )</span></span><br><span class="line">            alert(xhr.responseText)</span><br><span class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (xhr.status === <span class="number">404</span>) &#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">'404 not found'</span>)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> postData = &#123;</span><br><span class="line">	name:<span class="string">"zhangsan"</span>,</span><br><span class="line">	passsword:<span class="string">"xxx"</span></span><br><span class="line">]</span><br><span class="line">xhr.send(<span class="built_in">JSON</span>.stringify(postData))</span><br></pre></td></tr></table></figure>
<h2 id="状态码"><a href="#状态码" class="headerlink" title="状态码"></a>状态码</h2><h3 id="xhr-readyState"><a href="#xhr-readyState" class="headerlink" title="xhr.readyState"></a>xhr.readyState</h3><ul>
<li>0-（未初始化）还没有调用send()方法</li>
<li>1-（载入）已调用send()方法，正在发送请求</li>
<li>2-（载入完成）send()方法执行完成，已经接收到全部响应内容</li>
<li>3-（交互）正在解析响应内容</li>
<li>4-（完成）响应内容解析完成，可以再客户端调用</li>
</ul>
<h3 id="xhr-status"><a href="#xhr-status" class="headerlink" title="xhr.status"></a>xhr.status</h3><ul>
<li>2xx-表示成功处理请求，如200</li>
<li>3xx-需要重定向，浏览器直接跳转，如301,302,304</li>
<li>4xx-客户端请求错误，如404,403</li>
<li>5xx-服务器端错误</li>
</ul>
<h2 id="跨域：同源策略，跨域解决方案"><a href="#跨域：同源策略，跨域解决方案" class="headerlink" title="跨域：同源策略，跨域解决方案"></a>跨域：同源策略，跨域解决方案</h2><h3 id="同源策略"><a href="#同源策略" class="headerlink" title="同源策略"></a>同源策略</h3><ol>
<li><p>ajax请求时，浏览器要求当前网页和server必须同源（安全）</p>
</li>
<li><p>同源：协议、域名、端口，三者必须一致</p>
</li>
<li><p>前端：<a href="http://a.com:8080/" target="_blank" rel="noopener">http://a.com:8080/</a>;</p>
<p>server：<a href="https://b.com/api/xxx" target="_blank" rel="noopener">https://b.com/api/xxx</a></p>
<p>(线上默认80端口）</p>
</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//加载图片 css js 可无视同源策略</span></span><br><span class="line">	<span class="comment">//1.&lt;img src=跨域的图片地址 /&gt;</span></span><br><span class="line">	<span class="comment">//2.&lt;link href=跨域的css地址 /&gt;</span></span><br><span class="line">	<span class="comment">//3.&lt;script src=跨域的js地址&gt;&lt;/script&gt;</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//加载图片 css js 可无视同源策略</span></span><br><span class="line">	<span class="comment">//1.&lt;img /&gt;可用于统计打点，可使用第三方统计服务</span></span><br><span class="line">	<span class="comment">//2.&lt;link /&gt;&lt;script /&gt;可使用CDN，CDN一般都是外域</span></span><br><span class="line">	<span class="comment">//3.&lt;script&gt;可实现JSONP</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//跨域</span></span><br><span class="line">	<span class="comment">//1.所有的跨域，都必须经过server端允许和配合</span></span><br><span class="line">	<span class="comment">//2.未经server端允许就实现跨域，说明浏览器有漏洞，危险信号</span></span><br></pre></td></tr></table></figure>
<h3 id="JSONP"><a href="#JSONP" class="headerlink" title="JSONP"></a>JSONP</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//访问https://imooc.com/，服务端一定返回一个html文件吗？</span></span><br><span class="line"><span class="comment">//服务器可以任意动态拼接数据返回，只要符合html格式要求</span></span><br><span class="line"><span class="comment">//同理于&lt;script src="https://imooc.com/getData.js"&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//&lt;script&gt;可绕过跨域限制</span></span><br><span class="line"><span class="comment">//服务器可以任意动态拼接数据返回</span></span><br><span class="line"><span class="comment">//所以，&lt;script&gt;就可以获得跨域的数据，只要服务端愿意返回</span></span><br></pre></td></tr></table></figure>
<p>jsonp.html</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1.0"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"ie=edge"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>jsonp 演示<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">p</span>&gt;</span>一段文字 1<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"></span><br><span class="line">        <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">            <span class="built_in">window</span>.abc = <span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            	<span class="comment">//这是我们跨域得到的信息</span></span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(data)<span class="comment">//&#123; name: 'xxx' &#125;</span></span></span><br><span class="line"><span class="undefined">            &#125;</span></span><br><span class="line"><span class="undefined">        </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"http://localhost:8002/jsonp.js?username=xxx&amp;callback=abc"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>jsonp.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">abc(</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">'xxx'</span> &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>
<p>JSONP的原理：</p>
<ul>
<li><strong>本质上是利用HTML元素的**</strong>src属性**都可以跨域的思路来解决的</li>
<li><strong>创建一个回调函数，然后在远程服务上调用这个函数并且将JSON 数据形式作为参数传递，完成回调</strong></li>
</ul>
<p>具体可以查看<a href="https://www.cnblogs.com/soyxiaobi/p/9616011.html" target="_blank" rel="noopener">彻底弄懂jsonp原理及实现方法</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//jQuery实现jsonp</span></span><br><span class="line">$.ajax(&#123;</span><br><span class="line">    url:<span class="string">'http://localhost:8882/x-origin.json'</span>,</span><br><span class="line">    dataType:<span class="string">"jsonp"</span>,</span><br><span class="line">    jsonpCallback:<span class="string">"callback"</span>,</span><br><span class="line">    success:<span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(data);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h3 id="CORS（服务端支持）-服务器设置http-header"><a href="#CORS（服务端支持）-服务器设置http-header" class="headerlink" title="CORS（服务端支持）- 服务器设置http header"></a>CORS（服务端支持）- 服务器设置http header</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//第二个参数填写允许跨域的域名称，不建议直接写“*”</span></span><br><span class="line">response.setHeader(<span class="string">"Access-Control-Allow-Origin"</span>,<span class="string">"http://locaohost:8011"</span>)</span><br><span class="line">response.setHeader(<span class="string">"Access-Control-Allow-Headers"</span>,<span class="string">"X-Requested-With"</span>)</span><br><span class="line">response.setHeader(<span class="string">"Access-Control-Allow-Methods"</span>,<span class="string">"PUT,POST,GET,DELETE,OPTIONS"</span>)</span><br><span class="line"><span class="comment">//接受跨域的cookie</span></span><br><span class="line">response.setHeader(<span class="string">"Access-Control-Allow-Credentials"</span>,<span class="string">"true"</span>)</span><br></pre></td></tr></table></figure>
<h2 id="手写一个简易的Ajax"><a href="#手写一个简易的Ajax" class="headerlink" title="手写一个简易的Ajax"></a>手写一个简易的Ajax</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">url,successFn</span>) </span>&#123;</span><br><span class="line">     <span class="keyword">const</span> xhr = <span class="keyword">new</span> XMLHttpRequest()</span><br><span class="line">     xhr.open(<span class="string">'GET'</span>, url, <span class="literal">true</span>)</span><br><span class="line">     xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (xhr.readyState === <span class="number">4</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (xhr.status === <span class="number">200</span>) &#123;</span><br><span class="line">                    successFn(xhr.responseText)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    xhr.send(<span class="literal">null</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">url</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> p = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> xhr = <span class="keyword">new</span> XMLHttpRequest()</span><br><span class="line">        xhr.open(<span class="string">'GET'</span>, url, <span class="literal">true</span>)</span><br><span class="line">        xhr.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">if</span> (xhr.readyState === <span class="number">4</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (xhr.status === <span class="number">200</span>) &#123;</span><br><span class="line">                    resolve(</span><br><span class="line">                        <span class="built_in">JSON</span>.parse(xhr.responseText)</span><br><span class="line">                    )</span><br><span class="line">                &#125; <span class="keyword">else</span> <span class="keyword">if</span> (xhr.status === <span class="number">404</span> || xhr.status === <span class="number">500</span>) &#123;</span><br><span class="line">                    reject(<span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'404 not found'</span>))</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        xhr.send(<span class="literal">null</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="keyword">return</span> p</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> url = <span class="string">'/data/test.json'</span></span><br><span class="line">ajax(url)</span><br><span class="line">.then(<span class="function"><span class="params">res</span> =&gt;</span> <span class="built_in">console</span>.log(res))</span><br><span class="line">.catch(<span class="function"><span class="params">err</span> =&gt;</span> <span class="built_in">console</span>.error(err))</span><br></pre></td></tr></table></figure>
<h2 id="实际项目中ajax的常用插件"><a href="#实际项目中ajax的常用插件" class="headerlink" title="实际项目中ajax的常用插件"></a>实际项目中ajax的常用插件</h2><ul>
<li>$.ajax</li>
<li>fetch</li>
<li>axios</li>
</ul>
<h1 id="存储"><a href="#存储" class="headerlink" title="存储"></a>存储</h1><h2 id="cookie"><a href="#cookie" class="headerlink" title="cookie"></a>cookie</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">本身用于浏览器和server通讯</span><br><span class="line">被“借用”到本地存储来</span><br><span class="line">可用<span class="built_in">document</span>.cookie = <span class="string">'...'</span>来修改</span><br><span class="line"> </span><br><span class="line"></span><br><span class="line"><span class="built_in">document</span>.cookie = <span class="string">'a=100;b=200;'</span></span><br><span class="line"><span class="built_in">document</span>.cookie <span class="comment">//a=100</span></span><br><span class="line"><span class="built_in">document</span>.cookie = <span class="string">'b=200;'</span></span><br><span class="line"><span class="built_in">document</span>.cookie <span class="comment">//a=100; b=200</span></span><br><span class="line"><span class="built_in">document</span>.cookie = <span class="string">'a=300;'</span></span><br><span class="line"><span class="built_in">document</span>.cookie <span class="comment">//b=200; a=300</span></span><br><span class="line"><span class="built_in">document</span>.cookie = <span class="string">'d=400;'</span></span><br><span class="line"><span class="built_in">document</span>.cookie <span class="comment">//b=200; a=300;d=400;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//cookie缺点</span></span><br><span class="line">存储大小，最大<span class="number">4</span>KB</span><br><span class="line">http请求时需要发送到服务端，增加请求数据量</span><br><span class="line">只能用<span class="built_in">document</span>.cookie = <span class="string">'...'</span>来修改，太过简陋</span><br></pre></td></tr></table></figure>
<h2 id="localStorage和sessionStorage"><a href="#localStorage和sessionStorage" class="headerlink" title="localStorage和sessionStorage"></a>localStorage和sessionStorage</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">HTML5专门为存储而设计，最大可存<span class="number">5</span>M</span><br><span class="line">API简单易用setItem，getItem</span><br><span class="line">不会随着http请求被发送出去</span><br><span class="line"></span><br><span class="line">localStorage数据会永久存储，除非代码或手动删除</span><br><span class="line">sessionStorage数据只存在于当前会话，浏览器关闭则清空</span><br><span class="line">一般用localStorage会更多一些</span><br></pre></td></tr></table></figure>
<h2 id="描述cookie-localStorage-sessionStorage的区别"><a href="#描述cookie-localStorage-sessionStorage的区别" class="headerlink" title="描述cookie localStorage sessionStorage的区别"></a>描述cookie localStorage sessionStorage的区别</h2><ul>
<li>容量</li>
<li>API易用性</li>
<li>是否跟随http请求发送出去</li>
</ul>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Javascript/" rel="tag"># Javascript</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/10/29/javascript的循环遍历/" rel="next" title="javascript的循环遍历">
                <i class="fa fa-chevron-left"></i> javascript的循环遍历
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/10/30/vue常见面试题/" rel="prev" title="vue常见面试题">
                vue常见面试题 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="elfecho">
            
              <p class="site-author-name" itemprop="name">elfecho</p>
              <p class="site-description motion-element" itemprop="description">擅长各项前端技能，深入研究移动端开发与前端性能。非专业视觉设计师。此为博客一枚。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">29</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://elfeach.gitee.io/resume/" title="个人主页" target="_blank">个人主页</a>
                  </li>
                
              </ul>
            </div>
          
          <!-- 网易云音乐 
          <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=86 src="//music.163.com/outchain/player?type=2&id=31421442&auto=1&height=66"></iframe> -->

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#从JS基础知识到JS-WEB-API"><span class="nav-number">1.</span> <span class="nav-text">从JS基础知识到JS-WEB-API</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#DOM"><span class="nav-number">2.</span> <span class="nav-text">DOM</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#DOM的本质"><span class="nav-number">2.1.</span> <span class="nav-text">DOM的本质</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#DOM节点操作"><span class="nav-number">2.2.</span> <span class="nav-text">DOM节点操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#DOM结构操作"><span class="nav-number">2.3.</span> <span class="nav-text">DOM结构操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#DOM性能"><span class="nav-number">2.4.</span> <span class="nav-text">DOM性能</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#BOM"><span class="nav-number">3.</span> <span class="nav-text">BOM</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#事件"><span class="nav-number">4.</span> <span class="nav-text">事件</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#事件绑定"><span class="nav-number">4.1.</span> <span class="nav-text">事件绑定</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事件冒泡"><span class="nav-number">4.2.</span> <span class="nav-text">事件冒泡</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#事件代理"><span class="nav-number">4.3.</span> <span class="nav-text">事件代理</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Ajax"><span class="nav-number">5.</span> <span class="nav-text">Ajax</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#XMLHttpRequest"><span class="nav-number">5.1.</span> <span class="nav-text">XMLHttpRequest</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#状态码"><span class="nav-number">5.2.</span> <span class="nav-text">状态码</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#xhr-readyState"><span class="nav-number">5.2.1.</span> <span class="nav-text">xhr.readyState</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#xhr-status"><span class="nav-number">5.2.2.</span> <span class="nav-text">xhr.status</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#跨域：同源策略，跨域解决方案"><span class="nav-number">5.3.</span> <span class="nav-text">跨域：同源策略，跨域解决方案</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#同源策略"><span class="nav-number">5.3.1.</span> <span class="nav-text">同源策略</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#JSONP"><span class="nav-number">5.3.2.</span> <span class="nav-text">JSONP</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CORS（服务端支持）-服务器设置http-header"><span class="nav-number">5.3.3.</span> <span class="nav-text">CORS（服务端支持）- 服务器设置http header</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#手写一个简易的Ajax"><span class="nav-number">5.4.</span> <span class="nav-text">手写一个简易的Ajax</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实际项目中ajax的常用插件"><span class="nav-number">5.5.</span> <span class="nav-text">实际项目中ajax的常用插件</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#存储"><span class="nav-number">6.</span> <span class="nav-text">存储</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#cookie"><span class="nav-number">6.1.</span> <span class="nav-text">cookie</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#localStorage和sessionStorage"><span class="nav-number">6.2.</span> <span class="nav-text">localStorage和sessionStorage</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#描述cookie-localStorage-sessionStorage的区别"><span class="nav-number">6.3.</span> <span class="nav-text">描述cookie localStorage sessionStorage的区别</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">elfecho</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">39.6k</span>
  
</div>





        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
